package com.team9.fitness.controller;

import com.team9.fitness.entity.PostComment;
import com.team9.fitness.service.ZRDDSSendService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
import java.util.HashMap;
import java.util.concurrent.CompletableFuture;

/**
 * 帖子评论控制器
 */
@RestController
@RequestMapping("/api/post-comments")
@CrossOrigin(origins = { "*" }, allowCredentials = "false")
@Slf4j
public class PostCommentController {

    @Autowired
    private ZRDDSSendService zrddsSendService;

    /**
     * 创建评论
     */
    @PostMapping
    public CompletableFuture<ResponseEntity<Map<String, Object>>> createComment(@RequestBody Map<String, Object> requestBody) {

        log.info("创建帖子评论请求: {}", requestBody);

        // 从请求体中提取字段
        final Long postId = requestBody.get("postId") != null ? 
            Long.valueOf(requestBody.get("postId").toString()) : null;
        final Long userId = requestBody.get("userId") != null ? 
            Long.valueOf(requestBody.get("userId").toString()) : null;
        final String content = requestBody.get("content") != null ? 
            requestBody.get("content").toString() : null;
        final Long parentId = requestBody.get("parentId") != null ? 
            Long.valueOf(requestBody.get("parentId").toString()) : null;
        final Long rootId = requestBody.get("rootId") != null ? 
            Long.valueOf(requestBody.get("rootId").toString()) : null;

        log.info("创建帖子评论请求: postId={}, userId={}, parentId={}, rootId={}", postId, userId, parentId, rootId);

        // 创建PostComment对象
        PostComment comment = new PostComment();
        comment.setPostId(postId);
        comment.setUserId(userId);
        comment.setContent(content);
        comment.setParentId(parentId);
        comment.setRootId(rootId);
        
        log.info("创建的PostComment对象: postId={}, userId={}, parentId={}, rootId={}, content={}", 
                comment.getPostId(), comment.getUserId(), comment.getParentId(), comment.getRootId(), comment.getContent());

        Map<String, Object> requestBodyForZRDDS = new HashMap<>();
        requestBodyForZRDDS.put("comment", comment);

        return zrddsSendService.sendBusinessRequest("POST_COMMENT_CREATE", "POST", "/api/post-comments",
                userId != null ? userId.toString() : null, requestBodyForZRDDS)
                .thenApply(response -> {
                    Map<String, Object> result = new HashMap<>();
                    if (response.getSuccess()) {
                        result.put("success", true);
                        result.put("message", "评论创建成功");
                        result.put("data", response.getData());
                        log.info("评论创建成功: postId={}, userId={}", postId, userId);
                    } else {
                        result.put("success", false);
                        result.put("message", response.getMessage() != null ? response.getMessage() : "评论创建失败");
                        log.warn("评论创建失败: postId={}, userId={}, error={}", postId, userId, response.getError());
                    }
                    return ResponseEntity.ok(result);
                })
                .exceptionally(throwable -> {
                    log.error("评论创建异常: postId={}, userId={}", postId, userId, throwable);
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", false);
                    result.put("message", "评论创建服务异常，请稍后重试");
                    return ResponseEntity.ok(result);
                });
    }

    /**
     * 根据帖子ID获取评论列表
     */
    @GetMapping("/post/{postId}")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> getCommentsByPostId(@PathVariable Long postId,
            @RequestParam(required = false) Long currentUserId) {

        log.info("获取帖子评论列表请求: postId={}, currentUserId={}", postId, currentUserId);

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("postId", postId);
        if (currentUserId != null) {
            requestBody.put("currentUserId", currentUserId);
        }

        return zrddsSendService
                .sendBusinessRequest("POST_COMMENT_GET_BY_POST", "GET", "/api/post-comments/post/" + postId,
                        currentUserId != null ? currentUserId.toString() : null, requestBody)
                .thenApply(response -> {
                    Map<String, Object> result = new HashMap<>();
                    if (response.getSuccess()) {
                        result.put("success", true);
                        result.put("message", "获取评论列表成功");
                        result.put("data", response.getData());
                        log.info("获取评论列表成功: postId={}", postId);
                    } else {
                        result.put("success", false);
                        result.put("message", response.getMessage() != null ? response.getMessage() : "获取评论列表失败");
                        log.warn("获取评论列表失败: postId={}, error={}", postId, response.getError());
                    }
                    return ResponseEntity.ok(result);
                })
                .exceptionally(throwable -> {
                    log.error("获取评论列表异常: postId={}", postId, throwable);
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", false);
                    result.put("message", "获取评论列表服务异常，请稍后重试");
                    return ResponseEntity.ok(result);
                });
    }

    /**
     * 根据帖子id获取帖子评论总数
     */
    @GetMapping("/post/{postId}/count")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> getCommentCountByPostId(@PathVariable Long postId) {

        log.info("获取帖子评论总数请求: postId={}", postId);

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("postId", postId);

        return zrddsSendService
                .sendBusinessRequest("POST_COMMENT_GET_COUNT", "GET", "/api/post-comments/post/" + postId + "/count",
                        null, requestBody)
                .thenApply(response -> {
                    Map<String, Object> result = new HashMap<>();
                    if (response.getSuccess()) {
                        result.put("success", true);
                        result.put("message", "获取评论总数成功");
                        result.put("data", response.getData());
                        log.info("获取评论总数成功: postId={}", postId);
                    } else {
                        result.put("success", false);
                        result.put("message", response.getMessage() != null ? response.getMessage() : "获取评论总数失败");
                        log.warn("获取评论总数失败: postId={}, error={}", postId, response.getError());
                    }
                    return ResponseEntity.ok(result);
                })
                .exceptionally(throwable -> {
                    log.error("获取评论总数异常: postId={}", postId, throwable);
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", false);
                    result.put("message", "获取评论总数服务异常，请稍后重试");
                    return ResponseEntity.ok(result);
                });
    }

    /**
     * 获取用户评论列表
     */
    @GetMapping("/user/{userId}")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> getUserComments(@PathVariable Long userId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size) {

        log.info("获取用户评论列表请求: userId={}, page={}, size={}", userId, page, size);

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("userId", userId);
        requestBody.put("page", page);
        requestBody.put("size", size);

        return zrddsSendService.sendBusinessRequest("POST_COMMENT_GET_USER_COMMENTS", "GET", "/api/post-comments/user/" + userId,
                userId.toString(), requestBody)
                .thenApply(response -> {
                    Map<String, Object> result = new HashMap<>();
                    if (response.getSuccess()) {
                        result.put("success", true);
                        result.put("message", "获取用户评论列表成功");
                        result.put("data", response.getData());
                        log.info("获取用户评论列表成功: userId={}, page={}, size={}", userId, page, size);
                    } else {
                        result.put("success", false);
                        result.put("message", response.getMessage() != null ? response.getMessage() : "获取用户评论列表失败");
                        log.warn("获取用户评论列表失败: userId={}, page={}, size={}, error={}", userId, page, size, response.getError());
                    }
                    return ResponseEntity.ok(result);
                })
                .exceptionally(throwable -> {
                    log.error("获取用户评论列表异常: userId={}, page={}, size={}", userId, page, size, throwable);
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", false);
                    result.put("message", "获取用户评论列表服务异常，请稍后重试");
                    return ResponseEntity.ok(result);
                });
    }

    /**
     * 根据评论ID获取评论详情
     */
    @GetMapping("/{id}")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> getCommentById(@PathVariable Long id,
            @RequestParam(required = false) Long currentUserId) {

        log.info("获取评论详情请求: id={}, currentUserId={}", id, currentUserId);

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("id", id);
        if (currentUserId != null) {
            requestBody.put("currentUserId", currentUserId);
        }

        return zrddsSendService
                .sendBusinessRequest("POST_COMMENT_GET_BY_ID", "GET", "/api/post-comments/" + id,
                        currentUserId != null ? currentUserId.toString() : null, requestBody)
                .thenApply(response -> {
                    Map<String, Object> result = new HashMap<>();
                    if (response.getSuccess()) {
                        result.put("success", true);
                        result.put("message", "获取评论详情成功");
                        result.put("data", response.getData());
                        log.info("获取评论详情成功: id={}", id);
                    } else {
                        result.put("success", false);
                        result.put("message", response.getMessage() != null ? response.getMessage() : "获取评论详情失败");
                        log.warn("获取评论详情失败: id={}, error={}", id, response.getError());
                    }
                    return ResponseEntity.ok(result);
                })
                .exceptionally(throwable -> {
                    log.error("获取评论详情异常: id={}", id, throwable);
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", false);
                    result.put("message", "获取评论详情服务异常，请稍后重试");
                    return ResponseEntity.ok(result);
                });
    }

    /**
     * 根据评论ID获取回复列表
     */
    @GetMapping("/replies/{commentId}")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> getRepliesByCommentId(@PathVariable Long commentId,
            @RequestParam(required = false) Long currentUserId) {

        log.info("获取评论回复列表请求: commentId={}, currentUserId={}", commentId, currentUserId);

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("commentId", commentId);
        if (currentUserId != null) {
            requestBody.put("currentUserId", currentUserId);
        }

        return zrddsSendService
                .sendBusinessRequest("POST_COMMENT_GET_REPLIES", "GET", "/api/post-comments/replies/" + commentId,
                        currentUserId != null ? currentUserId.toString() : null, requestBody)
                .thenApply(response -> {
                    Map<String, Object> result = new HashMap<>();
                    if (response.getSuccess()) {
                        result.put("success", true);
                        result.put("message", "获取回复列表成功");
                        result.put("data", response.getData());
                        log.info("获取回复列表成功: commentId={}", commentId);
                    } else {
                        result.put("success", false);
                        result.put("message", response.getMessage() != null ? response.getMessage() : "获取回复列表失败");
                        log.warn("获取回复列表失败: commentId={}, error={}", commentId, response.getError());
                    }
                    return ResponseEntity.ok(result);
                })
                .exceptionally(throwable -> {
                    log.error("获取回复列表异常: commentId={}", commentId, throwable);
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", false);
                    result.put("message", "获取回复列表服务异常，请稍后重试");
                    return ResponseEntity.ok(result);
                });
    }

    /**
     * 删除评论
     */
    @DeleteMapping("/{id}")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> deleteComment(@PathVariable Long id,
            @RequestParam Long userId) {

        log.info("删除评论请求: commentId={}, userId={}", id, userId);

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("commentId", id);
        requestBody.put("userId", userId);

        return zrddsSendService.sendBusinessRequest("POST_COMMENT_DELETE", "DELETE", "/api/post-comments/" + id,
                userId.toString(), requestBody)
                .thenApply(response -> {
                    Map<String, Object> result = new HashMap<>();
                    if (response.getSuccess()) {
                        result.put("success", true);
                        result.put("message", "评论删除成功");
                        result.put("data", response.getData());
                        log.info("评论删除成功: commentId={}, userId={}", id, userId);
                    } else {
                        result.put("success", false);
                        result.put("message", response.getMessage() != null ? response.getMessage() : "评论删除失败");
                        log.warn("评论删除失败: commentId={}, userId={}, error={}", id, userId, response.getError());
                    }
                    return ResponseEntity.ok(result);
                })
                .exceptionally(throwable -> {
                    log.error("评论删除异常: commentId={}, userId={}", id, userId, throwable);
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", false);
                    result.put("message", "评论删除服务异常，请稍后重试");
                    return ResponseEntity.ok(result);
                });
    }
}
